class ChatReview {
    constructor(questions) {
        this.questions = questions;
        this.currentQuestion = 0;
        this.answers = [];
        this.messagesContainer = document.getElementById('chat-messages');
        this.userInput = document.getElementById('userInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.progress = document.getElementById('progress');
        this.saveExitBtn = document.getElementById('saveExitBtn');
        this.exitBtn = document.getElementById('exitBtn');
        this.completionActions = document.getElementById('completionActions');
        
        this.sendBtn.addEventListener('click', () => this.handleUserInput());
        this.userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.handleUserInput();
            }
        });

        // 添加保存退出和直接退出的事件监听
        this.saveExitBtn.addEventListener('click', () => this.handleSaveExit());
        this.exitBtn.addEventListener('click', () => this.handleExit());

        // 开始第一个问题
        setTimeout(() => this.askQuestion(), 1000);
    }

    async handleSaveExit() {
        if (this.answers.length === 0) {
            if (confirm('还没有回答任何问题，确定要退出吗？')) {
                window.location.href = '/';
            }
            return;
        }

        // 填充未回答的问题
        while (this.answers.length < this.questions.length) {
            this.answers.push('未完成');
        }

        this.addMessage('正在保存当前进度...', 'assistant');
        await this.saveReview();
        window.location.href = '/';
    }

    handleExit() {
        if (this.answers.length > 0) {
            if (!confirm('确定要退出吗？已回答的内容将不会保存。')) {
                return;
            }
        }
        window.location.href = '/';
    }

    async handleUserInput() {
        const answer = this.userInput.value.trim();
        if (!answer) return;

        // 添加用户回答到聊天
        this.addMessage(answer, 'user');
        this.userInput.value = '';
        this.answers.push(answer);

        // 更新进度条
        this.updateProgress();

        if (this.currentQuestion < this.questions.length - 1) {
            // 显示正在输入指示器
            this.showTypingIndicator();
            // 延迟显示下一个问题
            setTimeout(() => {
                this.currentQuestion++;
                this.askQuestion();
            }, 1000);
        } else {
            // 所有问题已回答完毕
            await this.finishReview();
        }
    }

    addMessage(content, type) {
        const message = document.createElement('div');
        message.className = `message ${type}`;
        message.textContent = content;
        this.messagesContainer.appendChild(message);
        this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
    }

    showTypingIndicator() {
        const indicator = document.createElement('div');
        indicator.className = 'typing-indicator message assistant';
        indicator.innerHTML = '<span></span><span></span><span></span>';
        this.messagesContainer.appendChild(indicator);
        this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
    }

    removeTypingIndicator() {
        const indicator = this.messagesContainer.querySelector('.typing-indicator');
        if (indicator) {
            indicator.remove();
        }
    }

    askQuestion() {
        this.removeTypingIndicator();
        this.addMessage(this.questions[this.currentQuestion], 'assistant');
    }

    updateProgress() {
        const progress = ((this.currentQuestion + 1) / this.questions.length) * 100;
        this.progress.style.width = `${progress}%`;
    }

    async saveReview() {
        try {
            const response = await fetch('/review', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    questions: this.questions,
                    answers: this.answers
                }),
            });

            if (!response.ok) {
                throw new Error('保存失败');
            }

            return await response.json();
        } catch (error) {
            alert('保存失败：' + error.message);
            throw error;
        }
    }

    async finishReview() {
        this.userInput.disabled = true;
        this.sendBtn.disabled = true;
        this.saveExitBtn.disabled = true;
        this.exitBtn.disabled = true;
        this.showTypingIndicator();

        try {
            const result = await this.saveReview();
            this.removeTypingIndicator();
            this.addMessage('感谢你的分享！让我来为你总结一下今天的复盘：', 'assistant');
            setTimeout(() => {
                this.addMessage(result.analysis, 'assistant');
                this.addMessage('复盘记录已保存。', 'assistant');
                this.completionActions.style.display = 'block';
            }, 1000);
        } catch (error) {
            this.removeTypingIndicator();
            this.addMessage(`保存失败：${error.message}`, 'assistant');
            this.userInput.disabled = false;
            this.sendBtn.disabled = false;
            this.saveExitBtn.disabled = false;
            this.exitBtn.disabled = false;
        }
    }
}

// 初始化聊天复盘
document.addEventListener('DOMContentLoaded', () => {
    new ChatReview(questions);
}); 